<template>
  <div>
    <div id="container">
      <item
        class="item"
        v-for="item in data_list"
        :item="item"
        :key="item._id"
      ></item>
    </div>
    <div class="add" @click="toAdd">
      <img src="add.png" />
    </div>
  </div>
</template>

<script>
import Item from "@/components/Item";
import axios from "axios";
import { Loading } from "element-ui";
export default {
  name: "Index",
  components: {
    Item,
  },
  data: function () {
    return {
      cursor: "0",
      has_more: true,
      data_list: [],
    };
  },
  methods: {
    handleScroll() {
      //内容实际高度
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      //滚动条滚动高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log("滚动到底部");
        if (this.has_more) this.getDataList();
      }
    },
    throttle(fn, delay) {
      let timer = null;
      return function (...rest) {
        let context = this;
        if (!timer) {
          timer = setTimeout(function () {
            fn(context, ...rest);
            timer = null;
          }, delay);
        }
      };
    },
    toAdd() {
      this.$router.push("/add");
    },
    async getDataList() {
      const loading = Loading.service({
        target: ".container",
      });
      let res = await axios.post(
        "https://qc3vk3.api.cloudendpoint.cn/getDataList",
        { cursor: this.cursor, limit: 20 }
      );
      const { data_list, has_more, cursor } = res.data;
      this.has_more = has_more;
      this.cursor = cursor;
      if (data_list?.length > 0) {
        this.data_list = this.data_list.concat(data_list);
      }
      loading.close();
    },
  },

  mounted() {
    this.handleScroll = this.throttle(this.handleScroll, 500);
    window.addEventListener("scroll", this.handleScroll);
    this.getDataList();
  },

  //destroyed只是卸下了组件，并没有销毁数据，只是把组件从dom中移除
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>

<style scoped>
#container {
  width: 1200px;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  margin: 0 auto;
}
.add {
  width: 150px;
  height: 150px;
  text-align: center;
  position: fixed;
  bottom: 20px;
  right: 20px;
}
img {
  width: 100px;
  height: 100px;
}
.item {
  flex: 1 1 250px;
  margin: 10px;
  height: 150px;
}
</style>
